package cn.edu.suda.ada.database.connection.pool;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.edu.suda.ada.common.config.Config;
import cn.edu.suda.ada.database.exception.DatabaseException;

public class C3p0ConnectionPool extends DefaultConnectionPool {
	ComboPooledDataSource dataSource;
	public C3p0ConnectionPool() {
		dataSource = new ComboPooledDataSource();
	}
	
	@Override
	public void init(Config config) throws DatabaseException {
		String url = config.getString("jdbc.url");
		String database = config.getString("jdbc.database");
		if (url.isEmpty()) {
			String link = config.getString("jdbc.link");
			String param = config.getString("jdbc.param");
			url = link + database + param;
		}
		
		try {
			dataSource.setDriverClass(config.getString("jdbc.driver"));
		} catch (PropertyVetoException e) {
			throw new DatabaseException("无法设置数据库驱动类！", e);
		}
		dataSource.setJdbcUrl(url);
		dataSource.setUser(config.getString("jdbc.username"));
		dataSource.setPassword(config.getString("jdbc.password"));
		
		dataSource.setMaxPoolSize(config.getInteger("c3p0.maxPoolSize"));
		dataSource.setInitialPoolSize(config.getInteger("c3p0.initialPoolSize"));
		dataSource.setMinPoolSize(config.getInteger("c3p0.minPoolSize"));
		dataSource.setMaxIdleTime(config.getInteger("c3p0.maxIdleTime"));
		dataSource.setAcquireIncrement(config.getInteger("c3p0.acquireIncrement"));
		dataSource.setMaxStatements(config.getInteger("c3p0.maxStatements"));
		dataSource.setIdleConnectionTestPeriod(config.getInteger("c3p0.idleConnectionTestPeriod"));
		dataSource.setAcquireRetryAttempts(config.getInteger("c3p0.acquireRetryAttempts"));
		dataSource.setBreakAfterAcquireFailure(config.getBoolean("c3p0.breakAfterAcquireFailure"));
		// TODO 支持所有配置参数
	}
	
	@Override
	public Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
}
